<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '订单详情',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full pos-relative z-1 bg-#F6F6F8">
      <wd-navbar @click-left="handleClickLeft">
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">订单详情</text>
        </template>
        <template #left>
          <wd-icon name="chevron-left" class="text-gray-333 font-size-44"></wd-icon>
        </template>
      </wd-navbar>
      <view class="w-full h-full home-content ps-b-180">
        <view>
          <view class="hr-160 p-x-28 flex justify-center flex-col box-bg">
            <view class="flex justify-between items-center">
              <view class="font-size-40 line-h-56 text-white font-500">{{ orderInfo.status }}</view>
              <view class="wr-56 hr-56">
                <image width="100%" height="100%" :src="statuIcons" />
              </view>
            </view>
          </view>
        </view>
        <!-- <view class="bg-white p-x-34 p-y-32">
          <view class="font-size-32 font-500 text-gray-333 line-h-44">
            上海市浦东新区居里路96号
          </view>
          <view class="font-size-28 font-400 text-gray-333 line-h-40 mg-t-20">
            <text>几遍</text>
            <text class="mg-l-5">15211178012</text>
          </view>
        </view> -->
        <view class="w-full bg-white mg-t-20">
          <view
            class="flex justify-start items-center p-x-28 p-y-34"
            v-for="(item, index) in productOrder"
            :key="index"
          >
            <wd-img
              :width="'160rpx'"
              :height="'160rpx'"
              custom-class="b-rd-8 overflow-hidden"
              :src="item.pic"
            />
            <view class="wr-500 mg-l-24">
              <view
                class="flex justify-between items-start font-size-28 font-500 text-gray-333 line-h-40"
              >
                <view>{{ item.name }}</view>
                <view class="mg-l-50">￥{{ item.price }}</view>
              </view>
              <view
                class="flex justify-between items-start font-size-24 font-400 text-gray-999 line-h-36 mg-t-24"
              >
                <view>{{ item.title }}</view>
                <view>X {{ item.num }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="flex justify-end bg-white p-x-28">
          <view class="wr-176 hr-72" v-if="statuType === 'confirm' || statuType === 'pay'">
            <wd-button type="info" plain size="small">
              <text class="font-size-28 font-500 text-gray-333">退款</text>
            </wd-button>
          </view>
          <view class="wr-176 hr-72" v-if="statuType === 'lookorder'">
            <wd-button type="info" plain size="small" @click="handleSendBack">
              <text class="font-size-28 font-500 text-gray-333">售后</text>
            </wd-button>
          </view>
        </view>
        <view class="p-x-28 p-y-34 border-box bg-white">
          <view class="w-100 hr-2 bg-#F5F5F5 mg-b-32"></view>
          <view class="flex justify-between items-center mg-b-40 font-size-28 text-gray-333">
            <view class="font-400">商品金额</view>
            <view class="font-500">
              <text>￥{{ orderInfo.pay_amount }}</text>
            </view>
          </view>
          <view class="flex justify-between items-center font-size-28 text-gray-333 mg-b-40">
            <view class="font-400">运费</view>
            <view class="font-500">
              <text>￥{{ orderInfo.deduct_amount }}</text>
            </view>
          </view>
          <view class="flex justify-between items-center font-size-28 mg-b-40 text-gray-333">
            <view class="font-400">优惠券</view>
            <view class="flex justify-center items-center">
              <text class="font-500 text-blue-1">{{ orderInfo.coupon_amount }}</text>
            </view>
          </view>
          <!-- <view class="flex justify-between items-center font-size-28 mg-b-40 text-gray-333">
            <view class="font-400">天琴币抵扣</view>
            <view class="flex justify-center items-center">
              <text class="font-500 text-blue-1">￥20</text>
            </view>
          </view> -->
          <view class="flex justify-end items-end font-size-28">
            <text class="text-gray-999 font-400 line-h-40">共{{ orderInfo.proNum }}件商品</text>
            <text class="text-gray-333 mg-l-12 line-h-40">实付 ￥</text>
            <text class="font-size-36 text-gray-333 line-h-46">{{ orderInfo.pay_amount }}</text>
          </view>
        </view>
        <view class="p-x-28 p-y-34 border-box bg-white mg-t-20" v-if="refundInfo?.address">
          <view class="font-size-32 font-500 text-gray-333">
            <text>物流信息</text>
          </view>
          <view class="bg-#F9F9F9 p-x-24 p-y-24 flex justify-start items-center mg-t-32">
            <view class="font-size-28 font-400 text-gray-999">
              <view>请将货物寄送至以下地址</view>
              <view>{{ refundInfo?.address }}</view>
            </view>
            <view class="wr-32 hr-32 mg-l-12" @click="toCopy">
              <image
                width="100%"
                height="100%"
                src="../../static/images/icons/copy.png"
                mode="scaleToFill"
              />
            </view>
          </view>
          <view class="hr-112 flex justify-between items-center">
            <view class="font-size-32 font-400 text-gray-666">
              <text>物流公司</text>
            </view>
            <view class="flex justify-end items-center">
              <!-- <view class="text-gray-999 font-size-32 font-400 mg-r-16">
                {{ expensInfo.company ? expensInfo.company : '请填写物流公司' }}
              </view>
              <wd-icon name="chevron-right" custom-class="text-gray-999 font-size-42"></wd-icon> -->
              <view class="text-gray-999 font-size-32 font-400 mg-r-16" v-if="!IsEdit">
                {{ expensInfo.company }}
              </view>
              <wd-picker
                v-else
                :columns="conpanyList"
                v-model="expensInfo.company"
                @confirm="handleConfirm"
              />
            </view>
          </view>
          <view class="hr-112 flex justify-between items-center bdr-b-#F5F5F5-2">
            <view class="font-size-32 font-400 text-gray-666">
              <text>物流单号</text>
            </view>
            <view class="flex justify-end items-center">
              <text v-if="!IsEdit">{{ expensInfo.orderCode }}</text>
              <text
                class="text-gray-333 font-size-32 font-500"
                @click="handleClickNickname"
                v-if="isEdit && IsEdit"
              >
                {{ expensInfo.orderCode }}
              </text>
              <wd-input
                v-if="IsEdit"
                custom-class="font-size-32 font-500 text-gray-333"
                custom-input-class="text-right font-size-32 font-500 text-gray-333"
                placeholder="请填写物流单号"
                type="text"
                v-model="expensInfo.orderCode"
                no-border
                @blur="isEdit = false"
              />
            </view>
          </view>
        </view>
        <div class="mg-t-20 ps-t-32 ps-b-1 bg-white" v-if="IsShowRefund">
          <view class="p-x-28 flex justify-between bg-white mg-b-40">
            <view class="font-size-28 font-400 text-gray-333 line-h-40 wr-186">退货类型</view>
            <view class="flex justify-center items-center">
              <text class="font-size-28 font-400 text-gray-999 line-h-40">
                {{ refundInfo.refund_no === '1' ? '退款退货' : '仅退款' }}
              </text>
            </view>
          </view>
          <view class="p-x-28 flex justify-between bg-white mg-b-40">
            <view class="font-size-28 font-400 text-gray-333 line-h-40 wr-186">退货理由</view>
            <view class="flex justify-center items-center">
              <text class="font-size-28 font-400 text-gray-999 line-h-40">
                {{ refundInfo.reason }}
              </text>
            </view>
          </view>
          <view class="p-x-28 flex justify-between bg-white mg-b-40">
            <view class="font-size-28 font-400 text-gray-333 line-h-40 wr-186">退货说明</view>
            <view class="flex justify-center items-center">
              <text class="font-size-28 font-400 text-gray-999 line-h-40">
                {{ refundInfo.remark }}
              </text>
            </view>
          </view>
          <view class="p-x-28 flex justify-between bg-white mg-b-40">
            <view class="font-size-28 font-400 text-gray-333 line-h-40 wr-186">凭证</view>
            <view class="flex justify-center items-center">
              <view
                class="wr-112 hr-112"
                v-for="(item, index) in refundInfo?.pics?.split(',')"
                :key="index"
              >
                <image width="100%" height="100%" :src="item" mode="scaleToFill" />
              </view>
              <!-- <text class="font-size-28 font-400 text-gray-999 line-h-40">
                {{ refundInfo.refund_no === '1' ? '退款退货' : '仅退款' }}
              </text> -->
            </view>
          </view>
        </div>
        <view class="mg-t-20 ps-t-32 ps-b-1 bg-white">
          <view
            class="p-x-28 flex justify-between bg-white mg-b-40"
            v-for="(item, index) in productInfo"
            :key="index"
          >
            <view class="font-size-28 font-400 text-gray-333 line-h-40 wr-186">
              {{ item.name }}
            </view>
            <view class="flex justify-center items-center">
              <text class="font-size-28 font-400 text-gray-999 line-h-40">{{ item.value }}</text>
            </view>
          </view>
        </view>
      </view>
      <view
        class="pos-absolute pos-bottom-0 pos-left-0 w-full hr-156 bg-white p-x-32 ps-t-14 b-solid-#F5F5F5-2 z-10"
        v-if="handleBtnList?.length > 0"
      >
        <view class="flex justify-end">
          <view class="wr-176 hr-72 mg-r-20" v-for="(item, index) in handleBtnList" :key="index">
            <wd-button
              custom-class=" text-white font-size-32"
              type="info"
              size="small"
              plain
              @click="handleBtn(item)"
            >
              <text class="font-size-28 font-400 text-gray-333">{{ item.name }}</text>
            </wd-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { getAppConfig } from '@/service/my/my'
import {
  cancelOrder,
  confirmReceive,
  getOrderDetail,
  postRefundExpress,
} from '@/service/order/order'
import { orderPay } from '@/service/shop/shop'
import { useMessage } from 'wot-design-uni'
import { useCopyText } from '@/hooks/useCopyText'

defineOptions({
  name: 'OrderDetail',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const handleClickLeft = () => {
  uni.navigateBack()
}
const productInfo = ref([
  {
    name: '订单号',
    value: '',
  },
  {
    name: '付款方式',
    value: '',
  },
  {
    name: '下单时间',
    value: '',
  },
  {
    name: '付款时间',
    value: '',
  },
  {
    name: '备注',
    value: '',
  },
])
const statuIcons = ref('../../static/images/icons/order-statu-1.png')
const statuType = ref('')
onLoad((options: any) => {
  statuType.value = options.type
})
const handleSendBack = () => {
  uni.navigateBack()
}
const handleBtnList: any = ref([])
// 订单状态:0=待付款,1=已完成,2=取消,3=待收货,4=待评价,5=售后中,6=售后通过待退货,7=售后通过待退款,8=退款中,9=售后完成,10=售后驳回,11=无效订单,12=待发货
// 售后单状态:0=审核中,1=成功,2=拒绝,3=失败,4=待退货,5=待退款,6=退款中
// 支付方式:0=天琴币,1=微信,2=支付宝
const IsEdit: any = ref(true)
const IsShowRefund: any = ref(false)
onShow(() => {
  const objStr: any = uni.getStorageSync('GoodsDetails')
  if (objStr) {
    const obj: any = JSON.parse(objStr)
    const btnGroup: any = obj.btns.filter((f: any) => {
      return f.name !== '查看订单'
    })
    handleBtnList.value = btnGroup
    const type: any = accrodByStatus(obj.status, obj)
    getData(obj.id, type)
  }
})
const savaCompanys: any = []
const getMyConfig = () => {
  getAppConfig().then((res: any) => {
    if (res.data) {
      const address: any = res.data.refund_address.value
      refundInfo.value.address = address
      const companyList: any = res.data.express
      for (let i = 0; i < Object.keys(companyList).length; i++) {
        const key = Object.keys(companyList)[i]
        const value = companyList[key]
        conpanyList.value.push(value)
        savaCompanys.push({
          key,
          value,
        })
      }
    }
  })
}
const accrodByStatus = (status: any, item: any) => {
  let type: any = 0
  IsEdit.value = true
  if (IsEdit.value === '退款中') {
    IsEdit.value = false
  }
  if (item.handleType === 'lookorder') {
    IsShowRefund.value = true
    IsEdit.value = false
  } else {
    IsShowRefund.value = false
  }
  if (
    status === '待付款' ||
    status === '已完成' ||
    status === '取消' ||
    status === '待收货' ||
    status === '待评价' ||
    status === '售后中' ||
    status === '售后通过待退货' ||
    status === '售后通过待退款' ||
    status === '退款中' ||
    status === '售后完成' ||
    status === '售后驳回' ||
    status === '无效订单' ||
    status === '售后完成' ||
    status === '无效订单' ||
    status === '待发货'
  ) {
    type = 0
  } else if (
    status === '审核中' ||
    status === '成功' ||
    status === '拒绝' ||
    status === '失败' ||
    status === '待退货' ||
    status === '待退款' ||
    status === '退款中'
  ) {
    type = 1
  }
  return type
}
const handleBtn = (btn: any) => {
  const item: any = orderInfo.value
  switch (btn.value) {
    case 'cancel': // 取消订单
      cancelOrderData(item)
      break
    case 'pay': // 支付
      toConfirmPage('pay', item)
      break
    case 'logistics': // 查看物流
      toLogisticsPage(item)
      break
    case 'comment': // 评价
      toCommentPage()
      break
    // case 'lookorder': // 查看订单
    //   toConfirmPage('lookorder', item)
    //   break
    case 'confirm': // 确认收货
      toConfirmPage('confirm', item)
      break
    case 'refund': // 申请退款
      toApplyRefundPage('refund', item)
      break
    // case 'reject': // 重新申请
    //   toApplyRefundPage('reject', item)
    // break
    case 'waitout': // 退货申请
      toApplyRefundPage('waitout', item)
      break
    // case 'moneyway':
    //   toOpenPage()
    // break
    case 'service':
      toServicePage()
      break
    case 'apply': //  申请退款
      toApplyRefundPage('apply', item)
      break
  }
}
const productOrder: any = ref([])

const orderInfo: any = ref({})
const refundInfo: any = ref({})
const getData = (id: any, type: any) => {
  getOrderDetail(id, type).then((res: any) => {
    if (res.data.order) {
      productOrder.value = res.data.order.orderGoods
      let num: any = 0
      productOrder.value.map((item: any) => {
        num += item.num
        return num
      })
      orderInfo.value.proNum = num
      orderInfo.value = res.data.order
      refundInfo.value = null
    } else {
      productOrder.value = res.data.orderGoods
      let num: any = 0
      productOrder.value.map((item: any) => {
        num += item.num
        return num
      })
      orderInfo.value.proNum = num
      orderInfo.value = res.data
      refundInfo.value = res.data.refundOrderInfo
      expensInfo.value.orderCode = refundInfo.value.express_no
      expensInfo.value.company = refundInfo.value.express_firm
    }
    if (refundInfo.value) {
      getMyConfig()
    }
    productInfo.value.map((item: any) => {
      if (item.name === '订单号') {
        item.value = orderInfo.value.order_no
      }
      if (item.name === '付款方式') {
        item.value = payTypeToText(orderInfo.value.pay_type)
      }
      if (item.name === '下单时间') {
        item.value = orderInfo.value.create_time
      }
      if (item.name === '付款时间') {
        item.value = orderInfo.value.pay_time
      }
      if (item.name === '备注') {
        item.value = orderInfo.value.remark
      }
      return item
    })
  })
}
const payTypeToText = (type: any) => {
  if (type === 1) {
    return '微信支付'
  } else if (type === 2) {
    return '支付宝支付'
  }
}
const toCommentPage = () => {
  uni.navigateTo({
    url: '/pages/orders/appraise',
  })
}
const applyPostData: any = {
  id: 0, // 订单id 必传
  refundId: 0, // 退款订单id 非必传 (再次提交必传)
  firm: '', // 公司
  address: '', // 地址联系方式
  expressNo: '', // 快递单号
}
const toApplyRefundPage = (type: string, item: any) => {
  item.handleType = type
  if (type === 'refund') {
    uni.setStorageSync('RefundDetails', JSON.stringify(item))
    uni.navigateTo({
      url: '/pages/orders/applyRefund',
    })
  } else if (type === 'apply') {
    uni.setStorageSync('RefundDetails', JSON.stringify(item))
    uni.navigateTo({
      url: '/pages/orders/applyRefund',
    })
  } else if (type === 'waitout') {
    if (expensInfo.value.orderCode) {
      uni.showToast({
        title: '请填写物流单号',
        icon: 'none',
      })
      return
    }
    if (expensInfo.value.company) {
      uni.showToast({
        title: '请选择物流公司',
        icon: 'none',
      })
      return
    }
    uni.showModal({
      content: '确认申请信息无误？',
      success: (res: any) => {
        if (res.confirm) {
          applyPostData.expressNo = expensInfo.value.orderCode
          applyPostData.id = item.id
          applyPostData.refundId = item.refundOrderInfo.id
          applyPostData.address = refundInfo.value.address
          console.log(applyPostData)
          postRefundExpress(applyPostData).then((res: any) => {
            uni.showToast({
              title: '退款申请成功！',
              icon: 'none',
              duration: 1000,
            })
          })
        }
      },
    })
  }
}
const payTools = usePayTool()
const toConfirmPage = (type: string, item: any) => {
  if (type === 'pay') {
    orderPay({ id: item.id }).then((res: any) => {
      payTools.payTool(res.data)
    })
  } else if (type === 'confirm') {
    uni.showModal({
      content: '确定收货吗？',
      success: (res: any) => {
        if (res.confirm) {
          confirmReceive(item.id).then((res: any) => {
            uni.showToast({
              title: '收货成功',
              icon: 'success',
              duration: 2000,
            })
          })
        }
      },
    })
  }
}
const reason: any = ref('')
const param: any = ref({
  id: '',
  reason: '',
})
const message = useMessage()
const cancelOrderData = (item: any) => {
  param.value.id = item.id
  message
    .prompt({
      title: '取消原因',
      inputValue: reason.value,
    })
    .then((resp) => {
      param.value.reason = resp.value
      cancelOrder(param.value).then((res: any) => {
        uni.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 2000,
        })
      })
    })
    .catch((res: any) => {
      console.log(res.action)
    })
}
const toLogisticsPage = (item: any) => {
  uni.setStorageSync('OrderExpress', JSON.stringify(item))
  uni.navigateTo({
    url: '/pages/transport/orderTransport' + '?id=' + item.id + '&type=0', // 类型:0=普通订单,1=售后订单
  })
}
const toServicePage = () => {
  uni.navigateTo({
    url: '/pages/customer/service',
  })
}
const isEdit: any = ref(false)
const handleClickNickname = () => {
  isEdit.value = true
}
const expensInfo: any = ref({
  orderCode: '',
  company: '',
})
const conpanyList: any = ref([])
const handleConfirm = (ev: any) => {
  const value: any = ev.value
  const findItem: any = savaCompanys.find((item: any) => item.value === value)
  if (findItem) {
    applyPostData.firm = findItem.value
  }
}
const cText: any = useCopyText()
const toCopy = () => {
  if (refundInfo.value?.address) {
    cText.copyText(String(refundInfo.value?.address))
  }
}
</script>

<style scoped lang="scss">
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
}
.box-bg {
  background: linear-gradient(138deg, #7195f8 0%, #aeb0ff 100%);
}
::v-deep .wd-search {
  padding: 0 !important;
  background: rgba(255, 255, 255, 0) !important;
}
::v-deep .wd-button {
  width: 100% !important;
  height: 100% !important;
}
::v-deep .wd-picker__cell {
  padding: 0 !important;
  font-size: 32rpx !important;
  color: #999 !important;
}
::v-deep .wd-picker__value {
  font-size: 32rpx !important;
  color: #999 !important;
}
::v-deep .wd-input__inner {
  font-size: 32rpx !important;
  color: #999 !important;
}
</style>
